<template>
	<div>
		<draggable v-model="imgList">
			<div
				v-for="(fileUrl, index) in imgList"
				:key="index"
				class="show-img"
			>
				<img
					class="show-avatar"
					:src="fileUrl"
					@click.stop="handleImagePreview(fileUrl)"
				/>
				<svg-icon
					class="show-delete"
					icon-class="bb_icon_delete"
					@click.stop="handleImageDelete(index)"
				/>
			</div>
		</draggable>
		<UploadItem
			v-if="isShowUpload"
			ref="imgUploadItem"
			size="mini"
			:uploadAPI="uploadAPI"
			:upload-file-type="'image'"
			:platform="'PC'"
			:fileSize="fileSize"
			:isShowImg="false"
			:disabled="disabled"
			@upoladItemSucess="handleUploadSucess"
			@startUpoladItem="handleStartUpload"
			@upoladItemDefeat="handleUploadDefeat"
		></UploadItem>
		<image-viewer
			v-if="imageViewerSrc"
			:visible.sync="imageViewerVisible"
			:url-list="[imageViewerSrc]"
		/>
	</div>
</template>

<script>
import draggable from 'vuedraggable'
import UploadItem from '@/components/UploadItemLimit'
export default {
	components: {
		draggable,
		UploadItem
	},
	props: {
		limit: {
			type: Number,
			default: 5
		},
		fileSize: {
			type: Number,
			default: 5 * 1024 * 1024
		},
		uploadAPI: {
			type: Function,
			default: () => {}
		}
	},
	data() {
		return {
			disabled: false,
			imgList: [],
			isShowUpload: true,
			imageViewerSrc: '',
			imageViewerVisible: false
		}
	},
	watch: {
		imgList: {
			handler(newVal) {
				this.isShowUpload = newVal.length < this.limit
				this.$emit('setImageAddress', this.imgList)
			}
		}
	},
	methods: {
		resetImgList() {
			this.imgList = []
		},
		handleImagePreview(fileUrl) {
			this.imageViewerSrc = fileUrl
			this.imageViewerVisible = true
		},
		handleImageDelete(index) {
			this.imgList = this.imgList.filter((val, key) => key !== index)
		},
		handleStartUpload() {
			this.disabled = true
			this.$message.info(this.$t('common.upload_start'))
		},
		handleUploadSucess({ index, file, id }) {
			this.disabled = false
			this.imgList.push(file.imgUrl)
		},
		handleUploadDefeat() {
			this.disabled = false
			this.$message.error(this.$t('common.upload_fail'))
		}
	}
}
</script>

<style lang="scss" scoped>
div {
	display: inline-block;
}

.show-img {
	margin-right: 5px;
	position: relative;
	.show-avatar {
		cursor: pointer;
		width: 100px;
		height: 100px;
	}
	.show-delete {
		cursor: pointer;
		z-index: 2;
		position: absolute;
		left: 80px;
		top: 0;
		text-align: center;
		font-size: 20px;
	}
}
</style>
